﻿using System;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Globalization;

namespace CustomControls
{
    /// <summary>
    /// This control is used to get mm/dd/yyyy format dates from textboxes. 
    /// Use DateTextBox where you need date format textbox in this project.
    /// </summary>
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:DateTextBox runat='server'></{0}:DateTextBox>")]
    [DebuggerDisplay("DateValue = {DateValue}, Text = {Text}")]
    public class DateTextBox : TextBox
    {
        private DateTime? _dateValue;
        private string[] DATE_FORMATS = { "MM/dd/yyyy", "MM.dd.yyyy" };
        public DateTextBox()
        {
        }

        public bool IsValidDate
        {
            get
            {
                if (String.IsNullOrWhiteSpace(this.Text))
                    return false;
                if (this.Text.Length != 10)
                    return false;
                if (!System.Text.RegularExpressions.Regex.IsMatch(this.Text, Resources.Global.DateRegex))
                    return false;
                return true;
            }
        }

        public DateTime? DateValue
        {
            get
            {
                if (IsValidDate)
                    return DateTime.ParseExact(this.Text, DATE_FORMATS, CultureInfo.InvariantCulture, DateTimeStyles.None);
                return null;
            }
            set
            {
                this._dateValue = value;
                this.Text = _dateValue.HasValue ? _dateValue.Value.ToString(DATE_FORMATS[0]) : "";
            }
        }


        public override string ToString()
        {
            return _dateValue.HasValue ? _dateValue.Value.ToString(DATE_FORMATS[0]) : "";
        }

        protected override void OnPreRender(EventArgs e)
        {
            StringBuilder datePickerScript = new StringBuilder();
            datePickerScript.Append(@"$(function () {$('#" + this.ClientID + "').datepicker({onSelect: function (dateText, inst) {$('#" + this.ClientID + "').attr('value',dateText);}});});");
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "AttachDatePicker", datePickerScript.ToString(), true);
            base.OnPreRender(e);
        }
    }
}